package ua.crimea.bat.ss.views;

import org.springframework.web.servlet.view.AbstractView;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.Map;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


/**
 * User: bat
 * Date: 02.04.2010
 * Time: 16:45:24
 */
public class JpegView extends AbstractView {

    /**
     * This constructor sets the appropriate content type "image/jpeg".
     */
    public JpegView() {
        setContentType("image/jpeg");
    }

    @SuppressWarnings("unchecked")
    protected final void renderMergedOutputModel(
            Map model, HttpServletRequest request, HttpServletResponse response) throws Exception {

        byte[] bytes = getData(model, request);

// Write content type and also length (determined via byte array).
        response.setContentType(getContentType());
        response.setContentLength(bytes.length);

// Flush byte array to servlet output stream.
        ServletOutputStream out = response.getOutputStream();
        out.write(bytes);
        out.flush();
    }

    @SuppressWarnings("unchecked")
    protected byte[] getData(Map model, HttpServletRequest request) {
        return (byte[]) model.get("imageData");
    }

    protected FileInputStream getFileInputStream(String path) throws FileNotFoundException {
        return new FileInputStream(path);
    }
}
